Back

Global Scope | booted method

Let's say you are trying to get users where active column is 1. Instead of writing every time

User::where('active',1);,

we can use Global Scopes. 

  • Create YourScope.php file inside app/Scopes folder.
  • Paste following code
<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class YourScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
       $builder->where('active', 1);
    }
}
  • And inside your Model add
protected static function booted()
{
  static::addGlobalScope(new YourScope());
}

Now, you when you call Users, you get only active ones.

Posted To avatar
Laravel
• 3 years ago

Please login or create an account to post a comment.

No Posts
No comments yet...